package org.victoria.common.controller;

import com.alibaba.fastjson.JSONObject;
import org.aspectj.util.FileUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.victoria.common.config.Config;
import org.victoria.common.utils.ResponseUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2015-1-26.
 */
@Controller
public class SupportController extends BaseController{

    /**
     * 图片上传
     * @param image
     * @param response
     * @param request
     */
    @RequestMapping("/uploadImage.htm")
    public void uploadImage(@RequestParam MultipartFile[] image,
                           HttpServletResponse response,
                           HttpServletRequest request) throws IOException {
        JSONObject object = ResponseUtil.getJsonObject();

        Map<File, InputStream> fileMap = new HashMap<File, InputStream>();
        List<String> urls = new ArrayList<String>();

        String base_path = request.getServletContext().getRealPath("/upload/images");
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        String[] date_path = format.format(new Date()).split("-");

        for(MultipartFile file : image){

            if (file.getSize()>2097152){
                object.put("code", 1);
                object.put("message", "图片大小请不要超过2M");
                ResponseUtil.renderJson(response, object.toString());
                return;
            }

            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
            if (!Arrays.asList(Config.IMAGE_SUFFIX.split(",")).contains(suffix)){
                object.put("code", 1);
                object.put("message", "不支持的图片类型");
                ResponseUtil.renderJson(response, object.toString());
                return;
            }

            String save_file_name = UUID.randomUUID().toString() + "." + suffix;
            String img_path = "/upload/images/" + date_path[0] + "/" + date_path[1] + "/" + save_file_name;
            String save_path = base_path + File.separator + date_path[0] + File.separator + date_path[1] + File.separator + save_file_name;
            try {
                File save_file = new File(save_path);
                if (!save_file.getParentFile().exists())
                    save_file.getParentFile().mkdirs();
                save_file.createNewFile();

                fileMap.put(save_file, file.getInputStream());
                urls.add(img_path);
            }catch (Exception e){
                object.put("code", 1);
                object.put("message", "服务器繁忙！");
                ResponseUtil.renderJson(response, object.toString());
            }

        }

        for (Map.Entry<File, InputStream> item : fileMap.entrySet()){
            OutputStream output = new FileOutputStream(item.getKey());
            FileUtil.copyStream(item.getValue(), output);
        }

        object.put("code", 0);
        object.put("url", urls);
        ResponseUtil.renderJson(response, object.toString());

    }

    @RequestMapping("/support/uploadFile.htm")
    public void uploadFile(@RequestParam MultipartFile[] files,
                           HttpServletResponse response,
                           HttpServletRequest request) throws IOException {
        JSONObject object = ResponseUtil.getJsonObject();

        Map<File, InputStream> fileMap = new HashMap<File, InputStream>();
        List<JSONObject> keyValue = new ArrayList<JSONObject>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
        String[] date_path = format.format(new Date()).split("-");

        for(MultipartFile file : files){

            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".")+1);
            String base_path = request.getServletContext().getRealPath("/upload/"+suffix);

            String save_file_name = UUID.randomUUID().toString() + "." + suffix;
            String img_path = "/upload/"+ suffix + date_path[0] + "/" + date_path[1] + "/" + save_file_name;
            String save_path = base_path + File.separator + date_path[0] + File.separator + date_path[1] + File.separator + save_file_name;
            try {
                File save_file = new File(save_path);
                if (!save_file.getParentFile().exists())
                    save_file.getParentFile().mkdirs();
                save_file.createNewFile();
                fileMap.put(save_file, file.getInputStream());
                JSONObject o = ResponseUtil.getJsonObject();
                o.put("fileName", fileName);
                o.put("url", img_path);
                keyValue.add(o);
            }catch (Exception e){
                object.put("code", 1);
                object.put("message", "服务器繁忙！");
                ResponseUtil.renderJson(response, object.toString());
            }

        }

        for (Map.Entry<File, InputStream> item : fileMap.entrySet()){
            OutputStream output = new FileOutputStream(item.getKey());
            FileUtil.copyStream(item.getValue(), output);
        }

        object.put("code", 0);
        object.put("file", keyValue);
        ResponseUtil.renderJson(response, object.toString());

    }

}
